<template>
	<view class="page-container">
		<!-- 自定义导航栏 -->
		<u-navbar :fixed="true" placeholder bgColor="transparent" :autoBack="true">
			<template #left>
				<view class="u-nav-slot">
					<u-icon name="arrow-left" size="19" color="#ffffff"></u-icon>
				</view>
			</template>
			<template #center>
				<view class="" style="color: #FFFFFF;">
					我要预约
				</view>
			</template>
		</u-navbar>
		<!-- 背景图容器 -->
		<view class="background-image-container">
			<image class="background-image" src="https://client-temple.shengxuankj.com/images/bookingPage_bg.png"
				mode="widthFix" lazy-load></image>
		</view>

		<!-- 主要内容区域 -->
		<view class="main-content">
			<view class="header-text">
				<view class="title">我要预约</view>
			</view>

			<!-- 白色内容卡片 -->
			<view class="content-card">
				<view class="form-title">预约信息</view>
				<!-- 表单区域 -->
				<view class="form-card">
					<u-form labelPosition="left" labelAlign="left" :model="formData" :rules="rules" ref="formRef" labelWidth="80">
						<u-form-item label="姓名" prop="name" borderBottom>
							<u-input v-model="formData.name" placeholder="请输入姓名" border="none"></u-input>
						</u-form-item>
					
						<u-form-item label="身份证" prop="card_no" borderBottom v-if="is_check == 0">
							<u-input v-model="formData.card_no" type="idcard" placeholder="请输入身份证号" border="none"
								@blur="handleIdCardBlur"></u-input>
						</u-form-item>
					
						<u-form-item label="年龄" prop="age" borderBottom>
							<u-input v-model="formData.age" type="number" placeholder="根据身份证自动计算或手动输入"
								border="none"></u-input>
						</u-form-item>
					
						<u-form-item label="性别" prop="sex" borderBottom>
							<u-radio-group v-model="formData.sex" placement="row">
								<u-radio :customStyle="{marginRight: '16px'}" label="男" name="男"></u-radio>
								<u-radio label="女" name="女"></u-radio>
							</u-radio-group>
						</u-form-item>
					
						<u-form-item label="手机号" prop="mobile" borderBottom v-if="is_check == 0">
							<u-input v-model="formData.mobile" type="number" placeholder="请输入手机号" border="none"></u-input>
						</u-form-item>
					
						<u-form-item label="预约日期" prop="datetime" borderBottom @click="showCalendar = true">
							<u-input v-model="formData.datetime" disabled disabledColor="#ffffff" placeholder="请选择预约日期"
								border="none"></u-input>
							<template #right>
								<u-icon name="arrow-right"></u-icon>
							</template>
						</u-form-item>
					</u-form>
				</view>
				

				<!-- 提交按钮 -->
				<view class="submit-btn">
					<u-button type="primary" text="立即预约" shape="circle" color="#9C4242" @click="submit"></u-button>
				</view>

				<!-- 日历组件 -->
				<u-calendar ref="calendarRef" :show="showCalendar" mode="single" @confirm="onCalendarConfirm"
					@close="showCalendar = false" :formatter="calendarFormatter" confirmText="确定" color="#9C4242" :defaultDate="initialDate"></u-calendar>


			</view>
		</view>
		
	</view>
</template>

<script setup lang="ts">
	import { onReady } from '@dcloudio/uni-app'
	import {
		ref,
		onMounted,
		reactive
	} from 'vue'
	import {
		indexInit,
		calendar,
		createOrder,
		get_openid
	} from '@/utils/api.js'

	const formRef = ref(null); // Form实例
	const calendarRef = ref(null); // 为 u-calendar 创建 ref
	const initialDate = ref('')
	const showCalendar = ref(false); // 控制日历显示
	// 表单数据
	const formData = reactive({
		open_id: uni.getStorageSync('openid'),
		name: '',
		card_no: '',
		age: '' as number | string,
		sex: '',
		mobile: '',
		datetime: '',
	});
	// 可预约的日期（从后端获取）
	const availableDates = ref([]);
	// --- Form Validation Rules ---
	const rules = reactive({
	  name: { type: 'string', required: true, message: '请输入姓名', trigger: ['blur', 'change'] },
	  sex: { type: 'string', required: true, message: '请选择性别', trigger: ['blur', 'change'] },
	  datetime: { type: 'string', required: true, message: '请选择预约日期', trigger: ['blur', 'change'] },
	  mobile: [
	    { required: true, message: '请输入手机号', trigger: ['blur', 'change'] },
	    { validator: (rule, value, callback) => uni.$u.test.mobile(value), message: '手机号码格式不正确' }
	  ],
	  card_no: [
	    { required: true, message: '请输入身份证号', trigger: ['blur', 'change'] },
	    { validator: (rule, value, callback) => uni.$u.test.idCard(value), message: '身份证号码格式不正确' }
	  ],
	  // 自定义年龄校验规则
	  age: [
	    { required: true, message: '请输入年龄', trigger: ['blur', 'change'] },
	    {
	      validator: (rule, value, callback) => {
	        if (!formData.card_no || !uni.$u.test.idCard(formData.card_no)) {
	          // 如果身份证号为空或格式不正确，则不进行此项校验
	          return true;
	        }
	        const calculatedAge = getAgeFromIdCard(formData.card_no);
	        // 允许1岁的误差
	        return Math.abs(Number(value) - calculatedAge) <= 1;
	      },
	      message: '年龄与身份证信息不符',
	      trigger: ['blur', 'change'],
	    }
	  ]
	});

	onMounted(async () => {
		await getCalendarData()
		await getCheck()
	})
	// onReady 是为了确保 formRef 已经挂载完毕
	onReady(() => {
		formRef.value.setRules(rules);
	  
		// 设置日历的 formatter 函数
	    // 确保 calendarRef 实例存在
	    if (calendarRef.value) {
	      calendarRef.value.setFormatter(calendarFormatter);
	    }
	});
	
	// 日历数据
	let disabledDays = []
	let dateList = ref([])
	const getCalendarData = () => {
		calendar().then(res => {
			console.log(res)
			if(res.code == 1){
				disabledDays = res.data.filter(item => item.status === 0).map(item => item.datetime); // 例：['2025-06-15', '2025-06-18']
				let objList = res.data.filter(item => item.status === 1).map(item => item.datetime); // 例：['2025-06-15', '2025-06-18']
				if(objList.length > 0){
					initialDate.value = objList[0]
				}else{
					initialDate.value = null
				}
				console.log(disabledDays)
				dateList.value = res.data
			}else{
				uni.showToast({ title: res.data.msg || '数据加载失败', icon: 'none' });
			}
		}).catch(error => {
			console.log(error)
		})
	}
	// 审核
	const is_check = ref(0)
	const getCheck = () => {
		indexInit().then(res => {
			if (res.code == 1) {
				is_check.value = res.data.is_check
			}
		})
	}

	// 模拟从后端获取可预约日期
	const fetchAvailableDates = async () => {
	  // 模拟API调用
	  await new Promise(resolve => setTimeout(resolve, 500));
	  // 假设后端返回了这些日期是可预约的
	  availableDates.value = ['2024-06-25', '2024-06-26', '2024-07-01', '2024-07-02'];
	  console.log('可预约日期已加载:', availableDates.value);
	};
	
	/**
	 * 日历格式化函数
	 * @param {object} day - 日历的day对象 {date, ...}
	 */
	const calendarFormatter = (day) => {
	  // uViewPlus 日期格式可能是 YYYY-MM-DD，而小程序日历可能是 YYYY/MM/DD
	  // 做一个兼容性处理，确保能正确匹配
	  const dateStr = uni.$u.timeFormat(day.date, 'yyyy-mm-dd');
	  // 检查是否在可预约列表中
	  if (disabledDays.length > 0 && disabledDays.includes(dateStr)) {
	  	day.disabled = true; // 如果不在可预约列表里，则禁用
		day.bottomInfo = '不可选'
	  }
	  return day;
	};
	
	/**
	 * 日历选择确认
	 * @param {string[]} dates - 选择的日期数组
	 */
	const onCalendarConfirm = (dates) => {
	  if (dates && dates.length > 0) {
		  let obj = dateList.value.find(item => item.datetime == dates[0])
		  if(obj.status == 0){
		  	uni.showToast({
		  		title: '选中的日期不可预约',
		  		icon: 'none',
		  		duration: 2000
		  	})
		  	return
		  }
	    formData.datetime = dates[0];
	    // 手动触发一下对 datetime 的校验
	    formRef.value.validateField('datetime');
	  }
	  showCalendar.value = false;
	};
	
	/**
	 * 身份证输入框失焦事件
	 */
	const handleIdCardBlur = () => {
	  if (formData.card_no && uni.$u.test.idCard(formData.card_no)) {
	    // 自动计算并填充年龄和性别
	    formData.age = getAgeFromIdCard(formData.card_no).toString();
		console.log('formData.age==============',formData.age)
		if( getGenderFromIdCard(formData.card_no) == '1' ){
			formData.sex = '男'
		}else{
			formData.sex = '女'
		}
	    
		console.log('formData.sex==============',formData.sex)
	    // 自动填充后，触发对 age 字段的校验
		// if(formData.age == ''){
		// 	formRef.value.validateField('age');
		// }
	  }
	};
	
	/**
	 * 提交表单
	 */
	const submit = async () => {
	  try {
		  if (!uni.getStorageSync('openid') || uni.getStorageSync('openid') == ''){
			  uni.login({
			  	success: (res) => {
			  		console.log(res)
			  		get_openid({
			  			code: res.code
			  		}).then(res => {
			  			console.log(res)
			  			if (res.code == 1) {
			  				uni.setStorageSync('openid', res.data.openid)
			  			}
			  		}).catch(error => {
			  			console.log(error)
			  		})
			  	}
			  })
			  
		  } 
	  	await formRef.value.validate();
	  	// uni.showToast({
	  	// 	title: '校验通过，准备提交',
	  	// 	icon: 'none',
	  	// 	duration: 2000
	  	// })
		
		// this.showMessage('校验通过');
		let obj = JSON.parse(JSON.stringify(formData))
		obj.age = Number(formData.age)
		createOrder(obj).then(res => {
			console.log(res)
			if (res.code == 1) {
				uni.showToast({
					title: '创建成功, 请耐心等待审核。',
					icon: 'none',
					duration: 2000,
					success() {
						let timer = setTimeout(()=>{
							uni.navigateTo({
								url: '/pages/history/index',
							})
							clearTimeout(timer)
						},1000)
					}
				})
				
			} else {
				uni.showToast({
					title: res.msg,
					icon: 'none',
					duration: 2000
				})
			}
		}).catch(error => {
			console.log(error)
		})
	  } catch (errors) {
	  	uni.showToast({
	  		title: '表单校验失败',
	  		icon: 'none',
	  		duration: 2000
	  	})
	  	console.log('校验失败详情:', errors);
	  }
	};
	
	// --- Helper Functions ---
	
	/**
	 * 从身份证号获取周岁年龄
	 * @param {string} idCard
	 * @returns {number}
	 */
	function getAgeFromIdCard(idCard) {
	  const birthYear = parseInt(idCard.substring(6, 10));
	  const birthMonth = parseInt(idCard.substring(10, 12));
	  const birthDay = parseInt(idCard.substring(12, 14));
	
	  const today = new Date();
	  const todayYear = today.getFullYear();
	  const todayMonth = today.getMonth() + 1;
	  const todayDay = today.getDate();
	
	  let age = todayYear - birthYear;
	  if (todayMonth < birthMonth || (todayMonth === birthMonth && todayDay < birthDay)) {
	    age--;
	  }
	  return age;
	}
	
	/**
	 * 从身份证号获取性别
	 * @param {string} idCard
	 * @returns {string} '1' for male, '2' for female
	 */
	function getGenderFromIdCard(idCard) {
	  const genderCode = parseInt(idCard.substring(16, 17));
	  return genderCode % 2 !== 0 ? '1' : '2'; // 奇数男，偶数女
	}
	
	// 分享功能
	const onShareAppMessage = () => {
		const promise = new Promise(resolve => {
			setTimeout(() => {
				resolve({
					title: '寺院预约'
				})
			}, 2000)
		})
		return {
			title: '寺院预约',
			path: '/pages/index/index',
			promise
		}
	}
	
	const onShareTimeline = () => {
		return {
			title: '寺院预约',
			query: '',
			imageUrl: 'https://client-temple.shengxuankj.com/images/home_bg.png'
		}
	}
</script>

<style lang="scss">
	.page-container {
		position: relative;
		min-height: 100vh;
		padding-bottom: 180rpx;
		box-sizing: border-box;
	}

	.van-nav-bar,
	.van-nav-bar__left,
	.van-nav-bar__title {
		background-color: transparent !important;
		color: #fff !important;
	}

	.van-nav-bar__title {
		font-weight: bold;
	}

	.background-image-container {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 800rpx;
		z-index: -1;
		overflow: hidden;
	}

	.background-image {
		width: 100%;
		height: 100%;
	}

	.main-content {
		position: absolute;
		top: 340rpx;
		left: 0;
		width: 100%;
	}

	.header-text .title {
		padding: 0 50rpx;
		color: #fff;
		font-size: 44rpx;
		font-weight: bold;
		margin-bottom: 40rpx;
	}

	.content-card {
		background-color: #fff;
		border-radius: 40rpx 40rpx 0 0;
		padding: 40rpx;
		box-sizing: border-box;
	}
	.form-card{
		width: 100%;
	}
	.form-title {
		font-size: 32rpx;
		font-weight: bold;
		margin-bottom: 20rpx;
	}

	.form-cell-group {
		margin: 0 !important;
		width: 100% !important;
		box-shadow: none;
	}

	.form-cell-group .van-cell {
		padding-left: 40rpx;
		padding-right: 40rpx;
	}

	.cell-value-active {
		color: #323233 !important;
	}

	.submit-button-wrapper {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		padding: 20rpx 40rpx;
		padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
		background-color: #fff;
		box-sizing: border-box;
	}

	/* 适配 Vant 组件在 UniApp 中的样式 */
	.van-cell {
		padding: 24rpx 32rpx !important;
	}

	.van-field__label {
		width: 160rpx !important;
	}

	.van-button--large {
		height: 96rpx !important;
		line-height: 96rpx !important;
		font-size: 32rpx !important;
	}

	/* 日期选择器样式调整 */
	.van-calendar__header {
		padding: 24rpx 0 !important;
	}

	.van-calendar__month-title {
		padding: 16rpx 32rpx !important;
	}

	.van-calendar__footer {
		padding: 16rpx 32rpx !important;
	}
	
	
	.submit-btn {
	  position: fixed;
	  bottom: 0;
	  left: 0;
	  width: 100%;
	  padding: 20rpx 40rpx;
	  padding-bottom: calc(20rpx + env(safe-area-inset-bottom)); /* 适配 iPhoneX 等机型 */
	  background-color: #fff;
	  box-sizing: border-box;
	}
</style>